/**
 * 
 */
package com.wubo.sec.util;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;

import com.wubo.common.util.Assert;
import com.wubo.common.util.ClassUtils;
import com.wubo.common.util.ReflectUtils;

/** 对象差异检查
 * 应用场景: 当一个对象被修改后检查修改了那些属性
 * @author WuBo
 * @CreateDate 2010-12-31
 * @version 1.0.1
 */
public abstract class ObjectDifferenceChecker {

	public static String check(Object old, Object obj){
		Assert.notNull(old);
		Assert.notNull(obj);
		Assert.isTrue(old.getClass().equals(obj.getClass()));
		
		StringBuilder sb = new StringBuilder();
		
		try{
			Field[] fields = ReflectUtils.getFields(old.getClass(), true);
			
			AccessibleObject.setAccessible(fields, true);
			for(int i=0; i<fields.length; i++){
				Field field = fields[i];
				
				if( ClassUtils.isNotDefinedClass(field.getType()) ){
					Object oldValue = field.get(old);
					Object newValue = field.get(obj);
					
					if( (oldValue != null && ! oldValue.equals(newValue))
						|| (oldValue == null && newValue != null) ){
						sb.append("["+field.getName()+":"+oldValue+"-->"+newValue+"]");
					}
				}
			}
		}catch(Exception e){
			throw new RuntimeException(e);
		}
		
		return sb.toString();
	}
	
	/*public static void main(String[] args){
		User user1 = new User();
		user1.setUsername("Admin");
		user1.setPassword("123456");
		user1.setEmail("asc@agilesc.com");
		user1.setActive(true);
		user1.setBirthday(new java.util.Date());
		
		User user2 = new User();
		user2.setUsername("wubo");
		user2.setPassword("123456");
		user2.setEmail("asc@agilesc.com.cn");
		user2.setActive(false);
		user2.setBirthday(new java.util.Date());
		
		System.out.println(check(user1, user2));
	}*/
}
